//
//  LLNWReachabilityManager.m
//  LLFoundation
//
//  Created by my_liu on 2016/11/14.
//  Copyright © 2016年 . All rights reserved.
//

#import "LLNWReachabilityManager.h"
#import "LLNWReachabilityAFNetworking.h"
#import "LLNWReachability.h"

NSString * const LLNWReachabilityDidChangeNotification = @"LLNWReachabilityDidChangeNotification";

@interface LLNWReachabilityManager ()
{
    id<LLNWReachabilityInterface> _reachability;
    LLNWStatus _lastStatus;
}
@end

@implementation LLNWReachabilityManager

+ (void)load
{
    [LLNWReachabilityManager share];
}

+ (instancetype)share
{
    static LLNWReachabilityManager *s = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        s = [[LLNWReachabilityManager alloc] init];
    });
    return s;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _reachability = [[LLNWReachabilityAFNetworking alloc] initWithDefault];
        [self startMonitoring];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(reachabilityChanged:)
                                                     name:LLNWReachabilityDidChangeNotification
                                                   object:nil];
    }
    return self;
}

- (void)reachabilityChanged:(NSNotification *)notification
{
    _lastStatus = _status;
    if ([_reachability isReachableViaWiFi]) {
        _status = LLNWStatusWifi;
    } else if ([_reachability isReachableViaWWAN]) {
        _status = LLNWStatusWWAN;
    } else if (![_reachability isReachable]) {
        _status = LLNWStatusNoReachable;
    } else {
        _status = LLNWStatusUnknow;
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:LLNWStatusChangedNotification object:[NSNumber numberWithInt:_status]];
    
    // 从无网到 有网
    if (_lastStatus == LLNWStatusNoReachable && (_status != LLNWStatusNoReachable && _status != LLNWStatusUnknow)) {
        [[NSNotificationCenter defaultCenter] postNotificationName:LLNWStatusNoneToReachNotification object:[NSNumber numberWithInt:_status]];
    }
    
    // 从有网 到 无网
    if ((_lastStatus != LLNWStatusNoReachable && _lastStatus != LLNWStatusUnknow) && _status == LLNWStatusNoReachable) {
        [[NSNotificationCenter defaultCenter] postNotificationName:LLNWStatusReachToNoneNotification object:[NSNumber numberWithInt:_status]];
    }
}

- (void)startMonitoring
{
    [_reachability startMonitoring];
}

- (void)stopMonitoring
{
    [_reachability stopMonitoring];
}

- (LLNWReachabilityStatus)networkReachabilityStatus
{
    return [_reachability networkReachabilityStatus];
}

- (BOOL)isReachable
{
    return [_reachability isReachable];
}

- (BOOL)isReachableViaWWAN
{
    return [_reachability isReachableViaWWAN];
}

- (BOOL)isReachableViaWiFi
{
    return [_reachability isReachableViaWiFi];
}

@end
